// @ts-ignore
import mapboxgl from 'mapbox-gl';
import React, { useEffect, useRef, useState, useCallback } from 'react';
import 'mapbox-gl/dist/mapbox-gl.css';

// 设置 Mapbox 访问令牌（实际项目中应该从环境变量获取）
mapboxgl.accessToken = 'pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';

interface Store {
  id: string;
  name: string;
  location: [number, number]; // [lng, lat]
  revenue: number;
  profit: number;
  customers: number;
  category: string;
  address: string;
  phone: string;
  manager: string;
}

interface MapboxMapProps {
  selectedRegion: string;
  onRegionChange: (region: string) => void;
  stores: Store[];
}

const MapboxMap: React.FC<MapboxMapProps> = ({ selectedRegion, onRegionChange, stores }) => {
  const mapContainer = useRef<HTMLDivElement>(null);
  const map = useRef<mapboxgl.Map | null>(null);
  const [popup, setPopup] = useState<mapboxgl.Popup | null>(null);

  // 模拟门店数据
  const mockStores: Store[] = [
    {
      id: '1',
      name: '北京朝阳店',
      location: [116.4074, 39.9042],
      revenue: 1200000,
      profit: 120000,
      customers: 2000,
      category: '综合超市',
      address: '北京市朝阳区建国路88号',
      phone: '010-12345678',
      manager: '张经理'
    },
    {
      id: '2',
      name: '上海浦东店',
      location: [121.4737, 31.2304],
      revenue: 900000,
      profit: 90000,
      customers: 1800,
      category: '综合超市',
      address: '上海市浦东新区陆家嘴金融区',
      phone: '021-87654321',
      manager: '李经理'
    },
    {
      id: '3',
      name: '广州天河店',
      location: [113.2644, 23.1291],
      revenue: 800000,
      profit: 70000,
      customers: 1700,
      category: '综合超市',
      address: '广州市天河区珠江新城',
      phone: '020-11223344',
      manager: '王经理'
    },
    {
      id: '4',
      name: '深圳南山店',
      location: [114.0579, 22.5431],
      revenue: 750000,
      profit: 65000,
      customers: 1600,
      category: '综合超市',
      address: '深圳市南山区科技园',
      phone: '0755-99887766',
      manager: '陈经理'
    },
    {
      id: '5',
      name: '杭州西湖店',
      location: [120.1551, 30.2741],
      revenue: 600000,
      profit: 60000,
      customers: 1500,
      category: '综合超市',
      address: '杭州市西湖区文三路',
      phone: '0571-33445566',
      manager: '刘经理'
    },
    {
      id: '6',
      name: '成都锦江店',
      location: [104.0668, 30.5728],
      revenue: 500000,
      profit: 50000,
      customers: 1400,
      category: '综合超市',
      address: '成都市锦江区春熙路',
      phone: '028-55667788',
      manager: '赵经理'
    },
    {
      id: '7',
      name: '重庆渝中店',
      location: [106.5516, 29.5630],
      revenue: 400000,
      profit: 35000,
      customers: 1200,
      category: '综合超市',
      address: '重庆市渝中区解放碑',
      phone: '023-77889900',
      manager: '孙经理'
    },
    {
      id: '8',
      name: '南京鼓楼店',
      location: [118.7969, 32.0603],
      revenue: 550000,
      profit: 55000,
      customers: 1300,
      category: '综合超市',
      address: '南京市鼓楼区中山路',
      phone: '025-11223344',
      manager: '周经理'
    },
    {
      id: '9',
      name: '西安雁塔店',
      location: [108.9480, 34.2632],
      revenue: 450000,
      profit: 40000,
      customers: 1100,
      category: '综合超市',
      address: '西安市雁塔区大雁塔',
      phone: '029-33445566',
      manager: '吴经理'
    },
    {
      id: '10',
      name: '武汉江汉店',
      location: [114.2986, 30.5844],
      revenue: 480000,
      profit: 43000,
      customers: 1150,
      category: '综合超市',
      address: '武汉市江汉区江汉路',
      phone: '027-55667788',
      manager: '郑经理'
    },
    {
      id: '11',
      name: '天津和平店',
      location: [117.1902, 39.1256],
      revenue: 520000,
      profit: 48000,
      customers: 1250,
      category: '综合超市',
      address: '天津市和平区和平路',
      phone: '022-77889900',
      manager: '孙经理'
    },
    {
      id: '12',
      name: '青岛市南店',
      location: [120.3826, 36.0671],
      revenue: 380000,
      profit: 32000,
      customers: 950,
      category: '综合超市',
      address: '青岛市市南区香港中路',
      phone: '0532-11223344',
      manager: '刘经理'
    },
    {
      id: '13',
      name: '大连中山店',
      location: [121.6186, 38.9146],
      revenue: 420000,
      profit: 38000,
      customers: 1050,
      category: '综合超市',
      address: '大连市中山区中山路',
      phone: '0411-33445566',
      manager: '王经理'
    },
    {
      id: '14',
      name: '厦门思明店',
      location: [118.0894, 24.4795],
      revenue: 350000,
      profit: 30000,
      customers: 900,
      category: '综合超市',
      address: '厦门市思明区中山路',
      phone: '0592-55667788',
      manager: '陈经理'
    },
    {
      id: '15',
      name: '苏州姑苏店',
      location: [120.5853, 31.2990],
      revenue: 580000,
      profit: 52000,
      customers: 1350,
      category: '综合超市',
      address: '苏州市姑苏区观前街',
      phone: '0512-77889900',
      manager: '李经理'
    }
  ];

  // 区域中心点坐标
  const regionCenters: Record<string, [number, number]> = {
    '北京': [116.4074, 39.9042],
    '上海': [121.4737, 31.2304],
    '广东': [113.2644, 23.1291],
    '江苏': [118.7969, 32.0603],
    '浙江': [120.1551, 30.2741],
    '四川': [104.0668, 30.5728],
    '重庆': [106.5516, 29.5630]
  };

  // 初始化地图
  useEffect(() => {
    if (map.current) return; // 防止重复初始化

    if (mapContainer.current) {
      map.current = new mapboxgl.Map({
        container: mapContainer.current,
        style: 'mapbox://styles/mapbox/light-v11',
        center: [104.0, 35.0], // 中国中心位置
        zoom: 4, // 更小的缩放级别以显示完整中国
        pitch: 0,
        bearing: 0,
        bounds: [
          [73.0, 18.0], // 西南角
          [135.0, 54.0]  // 东北角
        ]
      });

      // 添加导航控件
      map.current.addControl(new mapboxgl.NavigationControl(), 'top-right');

      // 添加全屏控件
      map.current.addControl(new mapboxgl.FullscreenControl(), 'top-right');

      // 地图加载完成后添加数据
      map.current.on('load', () => {
        addStoreMarkers();
        addHeatmapLayer();
        addRegionBoundaries();
      });
    }

    return () => {
      if (map.current) {
        map.current.remove();
        map.current = null;
      }
    };
  }, []);

  // 添加门店标记
  const addStoreMarkers = useCallback(() => {
    if (!map.current) return;

    // 添加门店数据源
    map.current.addSource('stores', {
      type: 'geojson',
      data: {
        type: 'FeatureCollection',
        features: mockStores.map(store => ({
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: store.location
          },
          properties: {
            id: store.id,
            name: store.name,
            revenue: store.revenue,
            profit: store.profit,
            customers: store.customers,
            category: store.category,
            address: store.address,
            phone: store.phone,
            manager: store.manager
          }
        }))
      }
    });

    // 添加门店标记图层
    map.current.addLayer({
      id: 'store-markers',
      type: 'circle',
      source: 'stores',
      paint: {
        'circle-radius': [
          'interpolate',
          ['linear'],
          ['get', 'revenue'],
          0, 8,
          2000000, 20
        ],
        'circle-color': [
          'interpolate',
          ['linear'],
          ['get', 'revenue'],
          0, '#ff6b6b',
          500000, '#ffa726',
          1000000, '#66bb6a',
          2000000, '#42a5f5'
        ],
        'circle-opacity': 0.8,
        'circle-stroke-width': 2,
        'circle-stroke-color': '#fff'
      }
    });

    // 添加门店标签
    map.current.addLayer({
      id: 'store-labels',
      type: 'symbol',
      source: 'stores',
      layout: {
        'text-field': ['get', 'name'],
        'text-font': ['Open Sans Regular'],
        'text-size': 12,
        'text-offset': [0, -2],
        'text-anchor': 'top'
      },
      paint: {
        'text-color': '#333',
        'text-halo-color': '#fff',
        'text-halo-width': 1
      }
    });

    // 点击门店显示弹窗
    map.current.on('click', 'store-markers', (e) => {
      if (!e.features || e.features.length === 0) return;

      const feature = e.features[0];
      const properties = feature.properties;
      
      if (!properties) return;

      // 创建弹窗内容
      const popupContent = `
        <div style="padding: 16px; max-width: 300px; font-family: Arial, sans-serif;">
          <h3 style="margin: 0 0 12px 0; color: #333; font-size: 18px;">${properties.name}</h3>
          <div style="margin-bottom: 8px;">
            <strong>地址：</strong>${properties.address}
          </div>
          <div style="margin-bottom: 8px;">
            <strong>电话：</strong>${properties.phone}
          </div>
          <div style="margin-bottom: 8px;">
            <strong>店长：</strong>${properties.manager}
          </div>
          <div style="margin-bottom: 8px;">
            <strong>营收：</strong>¥${properties.revenue.toLocaleString()}
          </div>
          <div style="margin-bottom: 8px;">
            <strong>利润：</strong>¥${properties.profit.toLocaleString()}
          </div>
          <div style="margin-bottom: 8px;">
            <strong>客户数：</strong>${properties.customers.toLocaleString()}
          </div>
          <div style="margin-bottom: 0;">
            <strong>类型：</strong>${properties.category}
          </div>
        </div>
      `;

      // 移除现有弹窗
      if (popup) {
        popup.remove();
      }

      // 创建新弹窗
      const newPopup = new mapboxgl.Popup({
        closeButton: true,
        closeOnClick: false,
        maxWidth: '400px'
      })
        .setLngLat((feature.geometry as any).coordinates)
        .setHTML(popupContent)
        .addTo(map.current!);

      setPopup(newPopup);
    });

    // 鼠标悬停效果
    map.current.on('mouseenter', 'store-markers', () => {
      if (map.current) {
        map.current.getCanvas().style.cursor = 'pointer';
      }
    });

    map.current.on('mouseleave', 'store-markers', () => {
      if (map.current) {
        map.current.getCanvas().style.cursor = '';
      }
    });
  }, [popup]);

  // 添加热力图层
  const addHeatmapLayer = useCallback(() => {
    if (!map.current) return;

    // 添加热力图数据源
    map.current.addSource('heatmap', {
      type: 'geojson',
      data: {
        type: 'FeatureCollection',
        features: mockStores.map(store => ({
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: store.location
          },
          properties: {
            weight: store.revenue / 10000 // 将营收转换为权重
          }
        }))
      }
    });

    // 添加热力图层
    map.current.addLayer({
      id: 'heatmap-layer',
      type: 'heatmap',
      source: 'heatmap',
      paint: {
        'heatmap-weight': [
          'interpolate',
          ['linear'],
          ['get', 'weight'],
          0, 0,
          200, 1
        ],
        'heatmap-intensity': [
          'interpolate',
          ['linear'],
          ['zoom'],
          0, 1,
          9, 3
        ],
        'heatmap-color': [
          'interpolate',
          ['linear'],
          ['heatmap-density'],
          0, 'rgba(0, 0, 255, 0)',
          0.2, 'rgba(0, 0, 255, 0.5)',
          0.4, 'rgba(0, 255, 255, 0.5)',
          0.6, 'rgba(0, 255, 0, 0.5)',
          0.8, 'rgba(255, 255, 0, 0.5)',
          1, 'rgba(255, 0, 0, 0.5)'
        ],
        'heatmap-radius': [
          'interpolate',
          ['linear'],
          ['zoom'],
          0, 2,
          9, 20
        ],
        'heatmap-opacity': 0.8
      }
    });
  }, []);

  // 添加区域边界
  const addRegionBoundaries = useCallback(() => {
    if (!map.current) return;

    // 这里可以添加区域边界数据
    // 实际项目中可以从 GeoJSON 文件加载
  }, []);

  // 根据选中区域更新地图视图
  useEffect(() => {
    if (!map.current || !selectedRegion) return;

    const center = regionCenters[selectedRegion];
    if (center) {
      map.current.flyTo({
        center: center,
        zoom: 8,
        duration: 2000
      });
    }
  }, [selectedRegion]);

  // 点击地图区域切换选中
  const handleMapClick = useCallback((e: any) => {
    // 这里可以实现点击地图区域来切换选中的区域
    // 需要加载区域边界数据并检测点击位置
    console.log('Map clicked at:', e.lngLat);
  }, []);

  useEffect(() => {
    if (!map.current) return;

    map.current.on('click', handleMapClick);

    return () => {
      if (map.current) {
        map.current.off('click', handleMapClick);
      }
    };
  }, [handleMapClick]);

  return (
    <div style={{ width: '100%', height: '600px', position: 'relative' }}>
      <div ref={mapContainer} style={{ width: '100%', height: '100%' }} />
      
      {/* 地图控制面板 */}
      <div style={{
        position: 'absolute',
        top: '10px',
        left: '10px',
        background: 'rgba(255, 255, 255, 0.95)',
        padding: '12px',
        borderRadius: '8px',
        boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
        zIndex: 1000,
        minWidth: '200px'
      }}>
        <div style={{ marginBottom: '10px', fontWeight: 'bold', fontSize: '14px' }}>地图控制</div>
        <div style={{ fontSize: '12px', color: '#666', lineHeight: '1.4' }}>
          <div>• 点击门店查看详情</div>
          <div>• 热力图显示营收分布</div>
          <div>• 支持区域筛选</div>
          <div>• 当前选中: {selectedRegion || '全部'}</div>
        </div>
        <div style={{ marginTop: '8px', display: 'flex', gap: '4px' }}>
          <button 
            onClick={() => {
              if (map.current) {
                map.current.flyTo({
                  center: [104.0, 35.0],
                  zoom: 4,
                  duration: 2000
                });
              }
            }}
            style={{
              padding: '4px 8px',
              fontSize: '11px',
              background: '#1890ff',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer'
            }}
          >
            重置视图
          </button>
        </div>
      </div>

      {/* 图例 */}
      <div style={{
        position: 'absolute',
        bottom: '10px',
        left: '10px',
        background: 'rgba(255, 255, 255, 0.95)',
        padding: '12px',
        borderRadius: '8px',
        boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
        zIndex: 1000,
        minWidth: '280px'
      }}>
        <div style={{ marginBottom: '10px', fontWeight: 'bold', fontSize: '14px' }}>门店规模图例</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '6px', fontSize: '12px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <div style={{ width: '8px', height: '8px', borderRadius: '50%', backgroundColor: '#ff6b6b' }}></div>
            <span>小型门店 (≤50万营收)</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <div style={{ width: '12px', height: '12px', borderRadius: '50%', backgroundColor: '#ffa726' }}></div>
            <span>中型门店 (50-80万营收)</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <div style={{ width: '16px', height: '16px', borderRadius: '50%', backgroundColor: '#66bb6a' }}></div>
            <span>大型门店 (80-120万营收)</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <div style={{ width: '20px', height: '20px', borderRadius: '50%', backgroundColor: '#42a5f5' }}></div>
            <span>超大型门店 (&gt;120万营收)</span>
          </div>
        </div>
        <div style={{ marginTop: '8px', paddingTop: '8px', borderTop: '1px solid #eee', fontSize: '11px', color: '#666' }}>
          热力图颜色: 蓝色(低) → 青色 → 绿色 → 黄色 → 红色(高)
        </div>
      </div>
    </div>
  );
};

export default MapboxMap; 